package itbour.onetouchshow.fragment.main;


import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andview.adapter.BaseRecyclerHolder;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ys.uilibrary.rv.AutoRecycleLayout;
import com.ys.uilibrary.utils.DisplayUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import itbour.onetouchshow.R;
import itbour.onetouchshow.adapter.FilterAdapter;
import itbour.onetouchshow.base.BaseRefreshAdapter;
import itbour.onetouchshow.base.mvp.SmartBaseRefreshFragment;
import itbour.onetouchshow.bean.AppBanner;
import itbour.onetouchshow.bean.DesignListBean;
import itbour.onetouchshow.bean.HomeDetailslBean;
import itbour.onetouchshow.bean.VideoConditionBean;
import itbour.onetouchshow.bean.eventbus.DetailsAction;
import itbour.onetouchshow.bean.page.Page;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.observable.NetWorkObservable;
import itbour.onetouchshow.service.ImagePorviderService;
import itbour.onetouchshow.singlecase.InchingDataSingleCase;
import itbour.onetouchshow.utils.ImageLoader;
import itbour.onetouchshow.utils.JumpUtils;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.SpUtils;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.recycleviewmanager.FastScrollManger;
import itbour.onetouchshow.widget.NoMoreDataViewFooter;
import itbour.onetouchshow.widget.ScaleImageView;

/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 *
 * @author onetouch
 *         <p>
 *         设计
 */

@SuppressLint("ValidFragment")
public class MainFragment extends SmartBaseRefreshFragment<MainContract.View, MainPresenter> implements MainContract.View, NetWorkObservable.NetWorkObserver {

    private static final int FAST_CLICK_DELAY_TIME = 2000;
    @BindView(R.id.id_recyclerview)
    public RecyclerView recyclerView;
    /**
     * 数据源
     */
    List<DesignListBean.ListBean> mdata = new ArrayList<>();
    /**
     * 后台数据
     */
    DesignListBean designListBean;
    Page page;
    @BindView(R.id.id_recyview_type)
    AutoRecycleLayout idRvType;
    @BindView(R.id.ry_time)
    RecyclerView ryTime;
    @BindView(R.id.ry_module)
    RecyclerView ryModule;
    @BindView(R.id.tv_filter_rule)
    TextView tvFilterRule;
    @BindView(R.id.ll_filter_layout)
    LinearLayout llFilterLayout;
    @BindView(R.id.tv_filter_name1)
    TextView tvFilterName1;
    @BindView(R.id.tv_filter_name2)
    TextView tvFilterName2;
    @BindView(R.id.ll_filter1)
    LinearLayout llFilter1;
    @BindView(R.id.ll_filter2)
    LinearLayout llFilter2;
    @BindView(R.id.iv_filter_rule)
    ImageView ivFilterRule;
    @BindView(R.id.ll_filter_rule)
    LinearLayout llFilterRule;
    Boolean isPullDownRefresh;
    NoMoreDataViewFooter noMoreDataViewFooter;
    FastScrollManger recyclerViewLayoutManager;
    View emptyView;
    private BaseQuickAdapter baseRefreshAdapter;
    /**
     * 根据ID 获取数据
     */
    private List<Integer> mids;
    private int index;
    private FilterAdapter filterAdapter1;
    private FilterAdapter filterAdapter2;
    //动画时间
    private int animationTime = 200;
    //两筛选条件
    private VideoConditionBean.Option filterRuleOption1;
    private VideoConditionBean.Option filterRuleOption2;
    //两筛选条件
    private VideoConditionBean.Option allRuleOption1;
    private VideoConditionBean.Option allRuleOption2;
    //是否执行了动画
    private boolean executeTheAnimation = false;
    private VideoConditionBean conditionBean;
    private long lastClickTime = 0L;
    private boolean isfrist = true;

    public MainFragment(int index, List<Integer> ids) {
        this.index = index;
        this.mids = ids;
    }

    public MainFragment() {

    }

    public void onLoadData() {
        page = new Page() {
            @Override
            public void load(int param1, int param2) {
                mPageIndex = param1;
                if (!isHaveMoreData()) {
                    mRefreshLayout.finishRefresh();
                    mRefreshLayout.finishLoadMoreWithNoMoreData();
                }
                if (mids == null) {
                    /**
                     * 异常后处理
                     */
                    List<Integer> exIds = new ArrayList<>();
                    String appID = SpUtils.getInstance().getString("AppID");
                    mids = new Gson().fromJson(appID, new TypeToken<List<Integer>>() {
                    }.getType());
                    if (mids == null) return;
                    if (index != 0) {
                        exIds.add(mids.get(index - 1));
                    } else {
                        exIds.addAll(mids);
                    }
                    mids = exIds;
                }
                mPresenter.getDetailsList(MainFragment.this, mids, getDurationKey(), getDurationValue(), getTmplTypeKey(), getTmplTypeValue());
                mPresenter.getAppBannerInfo();
            }
        };
        pullStatus = ON_REFRESH;
        page.loadPage(true);
    }

    /**
     * @return
     */
    public boolean isHaveMoreData() {
        return !(designListBean != null && mPageIndex >= designListBean.getTotalPage() - 1);
    }

    @Override
    public void loadSucceed(String result) {
        showContentView();
        isfrist = false;
        page.finishLoad(true);
        designListBean = new Gson().fromJson(result, DesignListBean.class);
        List<DesignListBean.ListBean> resultData = designListBean.getList();
        if (resultData == null || resultData.size() <= 0) {
            // T_.showToastReal("暂无数据");
            showErrorState(true);
            mRefreshLayout.finishLoadMoreWithNoMoreData();//设置之后，将不会再触发加载事件
            return;
        } else {
            baseRefreshAdapter.isUseEmpty(false);
        }
        DetailsAction detailsAction = new DetailsAction(AppConst.MAIN + MainFragment.this, resultData);
        ImagePorviderService.startService(getContext(), detailsAction);

    }

    public void endNetRequse(List<DesignListBean.ListBean> data) {
        showContentView();
        if (pullStatus == ON_LOAD) {
            mRefreshLayout.finishLoadMore(200);
            baseRefreshAdapter.addData(data);
        } else if (pullStatus == ON_REFRESH) {
            mRefreshLayout.finishRefresh(200);
            baseRefreshAdapter.replaceData(data);
            if (recyclerViewLayoutManager != null) {
                recyclerViewLayoutManager.scrollToPositionWithOffset(0, 0);
            }
        }
        if (data.size() < AppConst.PAGE_SIZE || !isHaveMoreData()) {
            mRefreshLayout.finishLoadMoreWithNoMoreData();//设置之后，将不会再触发加载事件
            baseRefreshAdapter.setFooterView(noMoreDataViewFooter = new NoMoreDataViewFooter(getContext()));
        } else {
            mRefreshLayout.setNoMoreData(false);
            if (noMoreDataViewFooter != null) {
                baseRefreshAdapter.removeFooterView(noMoreDataViewFooter);
            }
            baseRefreshAdapter.notifyItemChanged(baseRefreshAdapter.getLoadMoreViewPosition());
        }
        pullStatus = ON_REFRESH;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void dataEvent(DetailsAction detailsAction) {
        //  L_.e("dataEvent" + detailsAction);
        if (!detailsAction.getSubType().equals(AppConst.MAIN + MainFragment.this)) {
            return;
        }

        if (detailsAction.getData().size() == 0) {
            if (!isHaveMoreData()) {
                return;
            }
            showEmptyView();
            return;
        }

        endNetRequse(detailsAction.getData());
    }

    @Override
    public void loadFaild(String error) {
        page.finishLoad(false);
        showContentView();
        showErrorState(false);

    }


    public void showErrorState(boolean stateNodata) {
        endNetRequse(mdata = new ArrayList<>());
        ImageView imageView = emptyView.findViewById(R.id.id_state_icon);
        TextView textView = emptyView.findViewById(R.id.id_state_tv);
        if (stateNodata) {
            imageView.setImageResource(R.mipmap.ic_no_data);
            textView.setText("暂无数据");
        } else {
            imageView.setImageResource(R.mipmap.ic_no_network);
            textView.setText("暂无网络");
        }
        baseRefreshAdapter.isUseEmpty(true);
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
        lazyLoad();
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        EventBus.getDefault().register(this);
        // BaseApplication.instance().registerNetWorkObserver(this);
        // L_.e("mPresenter", mPresenter + "");
        UIUtils.getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                onLoadData();
            }
        }, AppConst.DELAYED_TIME);
    }

    @Override
    protected int getChirdLayoutId() {
        return R.layout.fragment_home_v6;
    }

    @Override
    protected void initView() {
        super.initView();
        idRvType.setVisibility(View.GONE);
        pullStatus = ON_REFRESH;
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {

                pullStatus = ON_REFRESH;
                if (mPresenter != null) {
                    page.loadPage(true);
                }
                // refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                //  refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
                pullStatus = ON_LOAD;
                if (mPresenter != null) {
                    page.loadPage(false);
                }

            }
        });

        initFilter();

    }

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void initRecycleView() {
        baseRefreshAdapter = getBaseRefreshAdapter();
        if (baseRefreshAdapter == null) {
            return;
        }

        recyclerView.setHasFixedSize(true);
        //使用瀑布流布局,第一个参数 spanCount 列数,第二个参数 orentation 排列方向
        // StaggeredGridLayoutManager recyclerViewLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        //recyclerView.setLayoutManager(recyclerViewLayoutManager);
        //使用瀑布流布局,第一个参数 spanCount 列数,第二个参数 orentation 排列方向
        recyclerViewLayoutManager = new FastScrollManger(2, StaggeredGridLayoutManager.VERTICAL);
        recyclerViewLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        recyclerView.setLayoutManager(recyclerViewLayoutManager);
        // baseRefreshAdapter.setHeaderView(getHeadView(), recyclerView);
        //recyclerView.setAdapter(baseRefreshAdapter);
        baseRefreshAdapter.bindToRecyclerView(recyclerView);
        //baseRefreshAdapter.isUseEmpty(true);
        emptyView = UIUtils.inflate(R.layout.view_no_data);
        baseRefreshAdapter.setEmptyView(emptyView);
        //   xRefreshView.setCustomHeaderView(getHeadView());
        baseRefreshAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();
                DesignListBean.ListBean listBean = (DesignListBean.ListBean) baseRefreshAdapter.getData().get(position);
                JumpUtils.goToVideoPlayer(getActivity(), listBean.getId());
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //Glide.with(getContext()).resumeRequests();
                    int lastBottomCompletelyEmergedItemPosition =
                            recyclerViewLayoutManager.findLastBottomCompletelyEmergedItemPosition();
                    if (lastBottomCompletelyEmergedItemPosition > 0) {
                        if (mImageViewRebackTop != null) {
                            mImageViewRebackTop.setVisibility(View.VISIBLE);
                        }

                    } else {
                        if (mImageViewRebackTop != null) {
                            mImageViewRebackTop.setVisibility(View.INVISIBLE);
                        }

                    }
                } else {
                    //   Glide.with(getContext()).pauseRequests();
                }
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    if (llFilterLayout.getVisibility() == View.GONE) return;
                    if (!executeTheAnimation && baseRefreshAdapter.getData().size() > 4) {
                        executeTheAnimation = true;
                        setFilterLayoutAlphaAnimation(1, 0, animationTime);
                        //上滑则缩起筛选条件 弹出筛选内容
//                        setFilterLayoutHeightAnimation(DisplayUtils.dip2px(getContext(),90), 0, animationTime);
                    }
                }

            }
        });


        mImageViewRebackTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recyclerViewLayoutManager.scrollToPositionWithOffset(0, 0);
                mImageViewRebackTop.setVisibility(View.INVISIBLE);
            }
        });
    }

    @Override
    public BaseQuickAdapter getBaseRefreshAdapter() {
        //    return baseRefreshAdapter = new MainAdapter(getContext(), mdata, R.layout.itme_main_frag_v3);
        return baseRefreshAdapter = new GirlAdapter();
    }

    @Override
    public View getHeadView() {
        return null;
    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("index", index);
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            index = savedInstanceState.getInt("index");
        }
        if (isFirstCreate) {
            //BaseApplication.instance().registerNetWorkObserver(this);
            showLoadingView();
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void loadPageInfoSuccess(String result) {
        L_.e(result);
        //new Gson().fromJson(result, ModelVideoBean.class);
    }

    @Override
    public void loadPageInfoFail(String result) {

    }

    @Override
    public void loadBannerSuccess(String response) {
        AppBanner appBanner = new Gson().fromJson(response, AppBanner.class);
        InchingDataSingleCase.INSTANCE.setAppBanner(appBanner);
    }

    @Override
    public void onNetWorkStatusChange(boolean b) {
        if (isfrist && b) {
            onLoadData();
        }
    }

    @Override
    public void onNewWorkEnvironment(NetWorkObservable.NetStateChangeEvent.NetState netState) {

    }

    @OnClick(R.id.ll_filter_rule)
    public void onViewClicked() {
        //  setFilterTextHeightAnimation(DisplayUtils.dip2px(getContext(), 45), 0, animationTime);
        setFilterTextAlphaAnimation(1, 0, animationTime);
    }

    private void initFilter() {
        filterAdapter1 = new FilterAdapter(getContext());
        filterAdapter2 = new FilterAdapter(getContext());
        ryTime.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        ryModule.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        ryTime.setAdapter(filterAdapter1);
        ryTime.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        ryModule.setAdapter(filterAdapter2);

        conditionBean = new Gson().fromJson(SpUtils.getInstance().getString(AppConst.APPBASEINFO), HomeDetailslBean.class).getVideoConditions();
        //以下皆为动态判断后台数据有空值 界面应正常显示
        if (conditionBean.getDurationCondition() != null) {
            if (conditionBean.getDurationCondition().getOptions() != null && conditionBean.getDurationCondition().getOptions().size() > 0 && conditionBean.getDurationCondition().getOptions().get(0) != null) {
                conditionBean.getDurationCondition().getOptions().get(0).setSelected(true);
                allRuleOption1 = conditionBean.getDurationCondition().getOptions().get(0);
            }
            setFilter1(conditionBean);
        } else {
            llFilter1.setVisibility(View.GONE);
        }
        if (conditionBean.getIndustryCondition() != null) {
            if (conditionBean.getIndustryCondition().getOptions() != null && conditionBean.getIndustryCondition().getOptions().size() > 0 && conditionBean.getIndustryCondition().getOptions().get(0) != null) {
                conditionBean.getIndustryCondition().getOptions().get(0).setSelected(true);
                allRuleOption2 = conditionBean.getIndustryCondition().getOptions().get(0);
            }
            setFilter2(conditionBean);
        } else {
            // llFilter2.setVisibility(View.GONE);
        }

        llFilterLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                llFilterLayout.requestDisallowInterceptTouchEvent(true);
                return true;
            }
        });
        ryModule.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                ryModule.requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });
        ryTime.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                ryTime.requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });

    }

    //Alpha动画
    private void setFilterLayoutAlphaAnimation(float form, float to, int time) {
        ValueAnimator va = ValueAnimator.ofFloat(form, to);
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                if (llFilterLayout.getVisibility() == View.GONE) {
                    llFilterLayout.setVisibility(View.VISIBLE);
                }
                float h = (Float) valueAnimator.getAnimatedValue();
                llFilterLayout.setAlpha(h);
            }


        });
        va.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if (form == 1) {
                    llFilterLayout.setVisibility(View.GONE);
                    llFilterLayout.setAlpha(1);
                    executeTheAnimation = false;
                    setFilterTextAlphaAnimation(0, 1, animationTime);
                    // setFilterLayoutHeightAnimation(DisplayUtils.dip2px(getContext(),90),DisplayUtils.dip2px(getContext(),40),animationTime);
                } else {
                    executeTheAnimation = false;
                }
            }
        });
        va.setDuration(time);
        va.start();
    }

    private void setFilterTextAlphaAnimation(float form, float to, int time) {
        ValueAnimator va = ValueAnimator.ofFloat(form, to);
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float h = (Float) valueAnimator.getAnimatedValue();
                if (llFilterRule.getVisibility() == View.GONE) {
                    llFilterRule.setVisibility(View.VISIBLE);
                }
                llFilterRule.setAlpha(h);
            }


        });
        va.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if (form == 1) {
                    //消失
                    llFilterRule.setVisibility(View.GONE);
                    llFilterRule.setAlpha(1);
                    setFilterLayoutAlphaAnimation(0, 1, animationTime);
                }
            }
        });
        va.setDuration(time);
        va.start();
    }

    //两行筛选缩起 弹出筛选条件 高度动画
    private void setFilterLayoutHeightAnimation(int form, int to, int time) {
        ValueAnimator va = ValueAnimator.ofInt(form, to);
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                int h = (Integer) valueAnimator.getAnimatedValue();
                llFilterLayout.getLayoutParams().height = h;
                llFilterLayout.requestLayout();
            }

        });
        va.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                //偏移量5dp
                if (llFilterLayout.getHeight() < DisplayUtils.dip2px(getActivity(), 5)) {
                    setFilterTextHeightAnimation(0, DisplayUtils.dip2px(getActivity(), 45), animationTime);
                } else {
                    executeTheAnimation = false;
                }
            }
        });
        va.setDuration(time);
        va.start();
    }

    //缩起筛选条件 弹出两行筛选
    private void setFilterTextHeightAnimation(int form, int to, int time) {
        ValueAnimator va = ValueAnimator.ofInt(form, to);
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                int h = (Integer) valueAnimator.getAnimatedValue();
                llFilterRule.getLayoutParams().height = h;
                llFilterRule.requestLayout();
            }

        });
        va.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                //偏移量5dp
                if (llFilterRule.getHeight() < DisplayUtils.dip2px(getActivity(), 5)) {
                    setFilterLayoutHeightAnimation(0, DisplayUtils.dip2px(getContext(), 90), animationTime);
                }
            }
        });

        va.setDuration(time);
        va.start();
    }

    //设置筛选1的选中
    private void setFilter1(VideoConditionBean videoConditionBean) {
        tvFilterName1.setText(videoConditionBean.getDurationCondition().getName());
        filterAdapter1.replaceAll(videoConditionBean.getDurationCondition().getOptions());
        filterAdapter1.setonItemClickListener(new FilterAdapter.onItemClickListener() {
            @Override
            public void onItemClickListener(int position, VideoConditionBean.Option option) {
                for (VideoConditionBean.Option o : filterAdapter1.getData()) {
                    o.setSelected(false);
                }
                filterAdapter1.getItem(position).setSelected(true);
                filterAdapter1.notifyDataSetChanged();
                filterRuleOption1 = option;
                if (position == 0) filterRuleOption1 = null;
                setRuleText();
                scrollToMiddle(ryTime, position);
            }
        });
    }

    private void scrollToMiddle(RecyclerView recyclerview, int position) {
        int firstPosition = ((LinearLayoutManager) recyclerview.getLayoutManager()).findFirstVisibleItemPosition();
        int lastPosition = ((LinearLayoutManager) recyclerview.getLayoutManager()).findLastVisibleItemPosition();
        int left = recyclerview.getChildAt(position - firstPosition).getLeft();
        int right = recyclerview.getChildAt(lastPosition - position).getLeft();
        recyclerview.scrollBy((left - right) / 2, 0);
    }

    //设置筛选2的选中
    private void setFilter2(VideoConditionBean videoConditionBean) {
        tvFilterName2.setText(videoConditionBean.getIndustryCondition().getName());
        filterAdapter2.replaceAll(videoConditionBean.getIndustryCondition().getOptions());
        filterAdapter2.setonItemClickListener(new FilterAdapter.onItemClickListener() {
            @Override
            public void onItemClickListener(int position, VideoConditionBean.Option option) {
                for (VideoConditionBean.Option o : filterAdapter2.getData()) {
                    o.setSelected(false);
                }
                filterAdapter2.getItem(position).setSelected(true);
                filterAdapter2.notifyDataSetChanged();
                filterRuleOption2 = option;
                if (position == 0) filterRuleOption2 = null;
                setRuleText();
                scrollToMiddle(ryModule, position);
            }
        });
    }

    //设置筛选条件内容
    private void setRuleText() {
        if (filterRuleOption1 == null && filterRuleOption2 == null) {
            ivFilterRule.setVisibility(View.VISIBLE);
            tvFilterRule.setText("筛选");
        } else if (filterRuleOption1 == null && filterRuleOption2 != null) {
            ivFilterRule.setVisibility(View.GONE);
            tvFilterRule.setText(filterRuleOption2.getName());
        } else if (filterRuleOption1 != null && filterRuleOption2 == null) {
            ivFilterRule.setVisibility(View.GONE);
            tvFilterRule.setText(filterRuleOption1.getName());
        } else {
            ivFilterRule.setVisibility(View.GONE);
            tvFilterRule.setText(filterRuleOption2.getName() + " • " + filterRuleOption1.getName());
        }
        onLoadData();


    }

    //组装key
    private String getDurationKey() {
        if (conditionBean == null) return null;
        else if (conditionBean != null) {
            if (conditionBean.getDurationCondition() == null)
                return null;
            else return conditionBean.getDurationCondition().getRequestKey();
        }
        return null;
    }

    //组装value
    private String getDurationValue() {
        if (filterRuleOption1 == null)
            return (allRuleOption1 == null ? "" : new Gson().toJson(allRuleOption1.getValues()));
        else return new Gson().toJson(filterRuleOption1.getValues());
    }

    //组装key
    private String getTmplTypeKey() {
        if (conditionBean == null) return null;
        else if (conditionBean != null) {
            if (conditionBean.getIndustryCondition() == null)
                return null;
            else return conditionBean.getIndustryCondition().getRequestKey();
        }
        return null;
    }

    //组装value
    private String getTmplTypeValue() {
        if (filterRuleOption2 == null)
            return (allRuleOption2 == null ? "" : new Gson().toJson(allRuleOption2.getValues()));
        else return new Gson().toJson(filterRuleOption2.getValues());
    }


    public class GirlAdapter extends BaseQuickAdapter<DesignListBean.ListBean, BaseViewHolder> {

        public GirlAdapter() {
            super(R.layout.itme_main_frag_v3);
        }

        public void deleteItem(int position) {
            remove(position);
            notifyDataSetChanged();
        }

        @Override
        protected void convert(BaseViewHolder helper, DesignListBean.ListBean listBean) {
            ScaleImageView imageView = helper.getView(R.id.id_ig);
            TextView tvName = helper.getView(R.id.id_tv_name);
            TextView tvCount = helper.getView(R.id.id_tv_count);
            // imageView.setInitSize(listBean.getW(),listBean.getH());
            ImageView vip = helper.getView(R.id.iv_vip_template);
            vip.setVisibility(listBean.isVipTemplate() ? View.VISIBLE : View.GONE);
            //  LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) imageView.getLayoutParams();
            // layoutParams.width = listBean.getW();
            // layoutParams.height = listBean.getH();
            imageView.setInitSize(listBean.getW(), listBean.getH());
            ImageLoader.getInstance().showCircleImageWithBorder(getContext(), listBean.getThumb(), imageView);
            tvName.setText(listBean.getName());
            tvCount.setText(listBean.getUseCounts() + "人使用");
//            helper.itemView.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    if (mOnItemClickListener != null) {
//                        mOnItemClickListener.onItemSelect(listBean);
//                    }
//                }
//            });
        }
    }


    public class MainAdapter extends BaseRefreshAdapter<DesignListBean.ListBean> {

        public MainAdapter(Context context, List<DesignListBean.ListBean> datas, int itemLayoutId) {
            super(context, datas, itemLayoutId);
        }

        @Override
        protected void convert(BaseRecyclerHolder viewHolder, DesignListBean.ListBean listBean, int position) {
            ScaleImageView imageView = viewHolder.getView(R.id.id_ig);
            TextView tvName = viewHolder.getView(R.id.id_tv_name);
            TextView tvCount = viewHolder.getView(R.id.id_tv_count);
            // imageView.setInitSize(listBean.getW(),listBean.getH());
            ImageView vip = viewHolder.getView(R.id.iv_vip_template);
            vip.setVisibility(listBean.isVipTemplate() ? View.VISIBLE : View.GONE);
            //  LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) imageView.getLayoutParams();
            // layoutParams.width = listBean.getW();
            // layoutParams.height = listBean.getH();
            imageView.setInitSize(listBean.getW(), listBean.getH());
            ImageLoader.getInstance().showCircleImageWithBorder(getContext(), listBean.getThumb(), imageView);
            tvName.setText(listBean.getName());
            tvCount.setText(listBean.getUseCounts() + "人使用");
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemClickListener != null) {
                        onItemClickListener.onItemSelect(listBean);
                    }
                }
            });
        }
    }


}
